﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;

namespace Thedog
{
    public partial class Form1 : Form
    {
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn
            (
                int nLeftRect,
                int nTopRect,
                int nRightRect,
                int nBottomRect,
                int nWidthEllipse,
                int nHeightEllipse
             );

        [DllImport("dwmapi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);

        [DllImport("dwmapi.dll")]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);

        [DllImport("dwmapi.dll")]
        public static extern int DwmIsCompositionEnabled(ref int pfEnabled);

        private bool m_aeroEnabled;
        private const int CS_DROPSHADOW = 0x00020000;
        private const int WM_NCPAINT = 0x0085;
        private const int WM_ACTIVATEAPP = 0x001C;

        public struct MARGINS
        {
            public int leftWidth;
            public int rightWidth;
            public int topHeight;
            public int bottomHeight;
        }

        private const int WM_NCHITTEST = 0x84;
        private const int HTCLIENT = 0x1;
        private const int HTCAPTION = 0x2;

        protected override CreateParams CreateParams
        {
            get
            {
                m_aeroEnabled = CheckAeroEnabled();

                CreateParams cp = base.CreateParams;
                if (!m_aeroEnabled)
                    cp.ClassStyle |= CS_DROPSHADOW;

                return cp;
            }
        }

        private bool CheckAeroEnabled()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                int enabled = 0;
                DwmIsCompositionEnabled(ref enabled);
                return (enabled == 1) ? true : false;
            }
            return false;
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCPAINT:
                    if (m_aeroEnabled)
                    {
                        var v = 2;
                        DwmSetWindowAttribute(this.Handle, 2, ref v, 4);
                        MARGINS margins = new MARGINS()
                        {
                            bottomHeight = 1,
                            leftWidth = 1,
                            rightWidth = 1,
                            topHeight = 1
                        };
                        DwmExtendFrameIntoClientArea(this.Handle, ref margins);

                    }
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
            //全窗体点击：最大化、最小化、移动窗体、双击最大化
            /*
            if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT)
                m.Result = (IntPtr)HTCAPTION;
            */
        }

        //绘制圆图片
        private Image CutEllipse(Image img, Rectangle rec, Size size)
        {
            Bitmap bitmap = new Bitmap(size.Width, size.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                using (TextureBrush br = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Clamp, rec))
                {
                    br.ScaleTransform(bitmap.Width / (float)rec.Width, bitmap.Height / (float)rec.Height);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.FillEllipse(br, new Rectangle(Point.Empty, size));
                }
            }
            return bitmap;
        }
        //对话框绘图
        private void Draw(Rectangle rectangle, Graphics g, int _radius, bool cusp, int orientation, Color begin_color, Color end_color)
        {
            int span = 2;
            //抗锯齿
            g.SmoothingMode = SmoothingMode.AntiAlias;
            //渐变填充
            LinearGradientBrush myLinearGradientBrush = new LinearGradientBrush(rectangle, begin_color, end_color, LinearGradientMode.Vertical);
            //画尖角
            if (cusp)
            {
                if (orientation == 0)
                {
                    span = 10;
                    PointF p1 = new PointF(rectangle.Width - 12, rectangle.Y + 10);
                    PointF p2 = new PointF(rectangle.Width - 12, rectangle.Y + 30);
                    PointF p3 = new PointF(rectangle.Width, rectangle.Y + 20);
                    PointF[] ptsArray = { p1, p2, p3 };
                    g.FillPolygon(myLinearGradientBrush, ptsArray);
                    g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                }
                else
                if (orientation == 1)
                {
                    span = 10;
                    PointF p1 = new PointF(12, rectangle.Y + 10);
                    PointF p2 = new PointF(12, rectangle.Y + 30);
                    PointF p3 = new PointF(0, rectangle.Y + 20);
                    PointF[] ptsArray = { p1, p2, p3 };
                    g.FillPolygon(myLinearGradientBrush, ptsArray);
                    g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X + span, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                }
                else
                {
                    g.FillPath(myLinearGradientBrush, DrawRoundRect(rectangle.X, rectangle.Y, rectangle.Width - span, rectangle.Height - 1, _radius));
                }
            }
        }
        public static GraphicsPath DrawRoundRect(int x, int y, int width, int height, int radius)
        {
            //四边圆角
            GraphicsPath gp = new GraphicsPath();
            gp.AddArc(x, y, radius, radius, 180, 90);
            gp.AddArc(width - radius, y, radius, radius, 270, 90);
            gp.AddArc(width - radius, height - radius, radius, radius, 0, 90);
            gp.AddArc(x, height - radius, radius, radius, 90, 90);
            gp.CloseAllFigures();
            return gp;
        }

        string UserName;
        public Form2 form2 = null; //插入表情窗口
        int limt, climt, set_x, cset_x; //滚动位置最大值和固定的左右的位置
        int Fmx, Fmy; //主窗口坐标
        bool mouse_Press = false, cmouse_Press = false; //鼠标按下
        bool mouse_Wheel = true, cmouse_Wheel = true; //鼠标滑轮事件
        Point mouseOff, cmouseOff; //存放当前鼠标位置
        string[,,] palte = new string[2, 7, 3]; //栏目
        public PicRichTextBox Rich_Edit; //编辑文字框
        

        int Chanel = 255; //对话频道值
        int OldChanel = -1; //前一个对话频道
        int Linewidth, Lineheight; //显示对话内容容器的宽度和高度
        bool linkFlag = false; //对话状态
        bool uw = false; //写入对话内容
        string getMess; //从服务端接受的数据
        private bool isExit = false; //连接状态
        private TcpClient client; //客户端
        private NetworkStream networkStream; //传输流
        private BinaryReader br; //读传输流
        private BinaryWriter bw; //写传输流

        public Form1(string us)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//解决非创建控件的线程调用控件报错
            m_aeroEnabled = false; //窗体四边阴影
            InitializeComponent();

            Me_Name.Text = us;
            UserName = us;
            ///////////////////////////////////////////////////////////////////////////
            Fmx = this.Left;
            Fmy = this.Top;
            //栏目内容
            palte[0, 0, 0] = "客服部";
            palte[0, 0, 1] = "心态要稳......";
            palte[0, 0, 2] =  @"Res\q1.jpg";

            palte[0, 1, 0] = "财务部";
            palte[0, 1, 1] = "向钱看......";
            palte[0, 1, 2] = @"Res\q2.jpg";

            palte[0, 2, 0] = "业务部";
            palte[0, 2, 1] = "加油加油加油......";
            palte[0, 2, 2] = @"Res\q3.jpg";

            palte[0, 3, 0] = "仓储部";
            palte[0, 3, 1] = "中华最香";
            palte[0, 3, 2] = @"Res\q1.jpg";

            palte[0, 4, 0] = "运输部";
            palte[0, 4, 1] = "20w";
            palte[0, 4, 2] = @"Res\q3.jpg";

            palte[0, 5, 0] = "";
            palte[0, 5, 1] = "";
            palte[0, 5, 2] = "";

            palte[0, 6, 0] = "";
            palte[0, 6, 1] = "";
            palte[0, 6, 2] = "";
            ///////////////////////////////////////////////////////////////////////////
            palte[1, 0, 0] = "流氓兔";
            palte[1, 0, 1] = "你是GAY吗？如果你是，我就是......";
            palte[1, 0, 2] = @"Res\tx1.jpg";

            palte[1, 1, 0] = "追着幸福跑";
            palte[1, 1, 1] = "如果有一天我忍不住问你，你一定要骗我......";
            palte[1, 1, 2] = @"Res\tx2.jpg";

            palte[1, 2, 0] = "壹個人好";
            palte[1, 2, 1] = "如果你有梦想的话，就要去捍卫它......";
            palte[1, 2, 2] = @"Res\tx3.jpg";

            palte[1, 3, 0] = "悢説芣炪";
            palte[1, 3, 1] = "每个成功的奥特曼背后总有个默默挨打的小怪兽......";
            palte[1, 3, 2] = @"Res\tx4.jpg";

            palte[1, 4, 0] = "喏訁巟訁";
            palte[1, 4, 1] = "帅有个屁用！到头来还不是被卒吃掉......";
            palte[1, 4, 2] = @"Res\tx5.jpg";

            palte[1, 5, 0] = "混丗魔王";
            palte[1, 5, 1] = "若注定是过客，何必去惊扰一盏灯光......";
            palte[1, 5, 2] = @"Res\tx6.jpg";

            palte[1, 6, 0] = "非主流";
            palte[1, 6, 1] = "别人手牵手，我牵我的狗，看谁不爽咬两口......";
            palte[1, 6, 2] = @"Res\tx7.jpg";
            //添加栏目
            Add_Palte();
            //栏目的鼠标事件
            Chanel_panel1.MouseLeave += new System.EventHandler(Panel_MouseLeave);
            Chanel_panel1.MouseMove += new MouseEventHandler(Panel_MouseMove);
            Chanel_panel2.MouseLeave += new System.EventHandler(Panel_MouseLeave);
            Chanel_panel2.MouseMove += new MouseEventHandler(Panel_MouseMove);
            Chanel_panel3.MouseLeave += new System.EventHandler(Panel_MouseLeave);
            Chanel_panel3.MouseMove += new MouseEventHandler(Panel_MouseMove);

            cp1.MouseLeave += new System.EventHandler(Pic_MouseLeave);
            cp1.MouseMove += new MouseEventHandler(Pic_MouseMove);
            cp2.MouseLeave += new System.EventHandler(Pic_MouseLeave);
            cp2.MouseMove += new MouseEventHandler(Pic_MouseMove);
            cp3.MouseLeave += new System.EventHandler(Pic_MouseLeave);
            cp3.MouseMove += new MouseEventHandler(Pic_MouseMove);

            Chn_1.MouseLeave += new System.EventHandler(Label_MouseLeave);
            Chn_1.MouseMove += new MouseEventHandler(Label_MouseMove);
            Chn_2.MouseLeave += new System.EventHandler(Label_MouseLeave);
            Chn_2.MouseMove += new MouseEventHandler(Label_MouseMove);
            Chn_3.MouseLeave += new System.EventHandler(Label_MouseLeave);
            Chn_3.MouseMove += new MouseEventHandler(Label_MouseMove);

            CNum1.MouseLeave += new System.EventHandler(Label_MouseLeave);
            CNum1.MouseMove += new MouseEventHandler(Label_MouseMove);
            CNum2.MouseLeave += new System.EventHandler(Label_MouseLeave);
            CNum2.MouseMove += new MouseEventHandler(Label_MouseMove);
            CNum3.MouseLeave += new System.EventHandler(Label_MouseLeave);
            CNum3.MouseMove += new MouseEventHandler(Label_MouseMove);

            Left_panel.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel_panel1.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel_panel2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel_panel3.MouseWheel += new MouseEventHandler(OnMouseWheel);
            cp1.MouseWheel += new MouseEventHandler(OnMouseWheel);
            cp2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            cp3.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chn_1.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chn_2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chn_3.MouseWheel += new MouseEventHandler(OnMouseWheel);
            CNum1.MouseWheel += new MouseEventHandler(OnMouseWheel);
            CNum2.MouseWheel += new MouseEventHandler(OnMouseWheel);
            CNum3.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel1_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel2_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            Chanel3_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
            //显示对话内容框鼠标事件
            Showinfo_panel.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
            //滚动条位置定义
            set_x = ScrollHard_panel.Location.X; //固定左右位置为当前位置
            limt = ScrollBar_panel.Height - ScrollHard_panel.Height; //滚动最大高度
            ScrollHard_panel.Location = new Point(set_x, 0); //先将位置设置到最顶

            cset_x = TakeScrollHard_panel.Location.X; //固定左右位置为当前位置
            climt = TakeScrollBar_panel.Height - TakeScrollHard_panel.Height; //滚动最大高度
            TakeScrollHard_panel.Location = new Point(cset_x, 0); //先将位置设置到最顶
            //信息编辑框属性
            Rich_Edit = new PicRichTextBox();
            Rich_Edit.Dock = DockStyle.Fill;
            Rich_Edit.BackColor = Color.FromArgb(213, 224, 230);
            Rich_Edit.BorderStyle = BorderStyle.None;
            Rich_Edit.ScrollBars = RichTextBoxScrollBars.None;
            Rich_Edit.KeyUp += new KeyEventHandler(RichEdit_KeyUp);
            Rich_Edit.TextChanged += new EventHandler(RichEdit_TextChanged);
            Edit_panel.Controls.Add(Rich_Edit);

            //建立网络通讯
            try
            {
                client = new TcpClient("127.0.0.1", 64787); //定义服务器端ip地址和端口，与服务器端定义要一致
                TcpInfo.AppendText("本机EndPoint：" + client.Client.LocalEndPoint); //本机的ip地址和端口号
                TcpInfo.AppendText("与服务器建立连接成功");
                linkFlag = true;
            }
            catch
            {
                TcpInfo.AppendText("与服务器连接失败");
                return;
            }
            if (linkFlag)
            {
                //获取网络流
                networkStream = client.GetStream();
                //将网络流作为二进制读写对象，使用UTF8编码
                br = new BinaryReader(networkStream);
                bw = new BinaryWriter(networkStream);
                SendString("Login");
                Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
                threadReceive.Start();
            }
        }
        //编辑框按键事件，是否影响需测试
        private void RichEdit_KeyUp(object sender, KeyEventArgs e)
        {
            /*
            if ((e.KeyCode == Keys.Delete) || (e.KeyCode == Keys.Back) || 
                (e.KeyCode==Keys.Up) || (e.KeyCode == Keys.Down) || (e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right) ||
                (e.KeyCode == Keys.Home) || (e.KeyCode == Keys.End) || (e.KeyCode == Keys.PageUp) || (e.KeyCode == Keys.PageDown))
            {
                this.Focus();
                Rich_Edit.Focus();
            }
            */
        }
        //编辑框文字改变，失去焦点在获得，引发编辑框和显示内容框重绘，从而显示动画和背景透明图片
        private void RichEdit_TextChanged(object sender, EventArgs e)
        {
            this.Focus();
            Rich_Edit.Focus();
        }

        //添加栏目
        private void Add_Palte()
        {
            for (int t = 1; t > -1; t--)
            {
                for (int i = 6; i > -1; i--)
                {
                    if (palte[t, i, 2] != "")
                    {
                        Panel Take_Chanel = new Panel();
                        PictureBox Pic_info = new PictureBox();
                        Label Brie_Info = new Label();
                        Label Num_Info = new Label();
                        Label Name_Info = new Label();

                        Pic_info.Size = new Size(64, 64);
                        Pic_info.Image = Image.FromFile(palte[t, i, 2]);
                        Image image = Pic_info.Image;
                        Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        Pic_info.Image = newImage;
                        Pic_info.Location = new Point(0, 5);
                        Pic_info.Cursor = Cursors.Hand;
                        Pic_info.Tag = ":Take:" + t + ":User:" + i;

                        Name_Info.Font = new Font("微软雅黑", 9);
                        Name_Info.ForeColor = Color.SteelBlue;
                        Name_Info.Text = palte[t, i, 0];
                        Name_Info.Location = new Point(70, 5);
                        Name_Info.Tag = ":Take:" + t + ":User:" + i;
                        Take_Chanel.Controls.Add(Name_Info);

                        Brie_Info.AutoSize = false;
                        Brie_Info.Width = 130;
                        Brie_Info.Height = 55;
                        Brie_Info.Text = palte[t, i, 1];
                        Brie_Info.BorderStyle = BorderStyle.None;
                        Brie_Info.Location = new Point(70, 28);
                        Brie_Info.BackColor = Color.FromArgb(255, 255, 255);
                        Brie_Info.Font = new Font("微软雅黑", 9);
                        Brie_Info.ForeColor = Color.FromArgb(120, 120, 120);
                        Brie_Info.Cursor = Cursors.Hand;
                        Brie_Info.Tag = ":Take:" + t + ":User:" + i;
                        Take_Chanel.Controls.Add(Brie_Info);

                        Num_Info.Font = new Font("微软雅黑", 9);
                        Num_Info.ForeColor = Color.SteelBlue;
                        Num_Info.Text = "[0.]";
                        Num_Info.Location = new Point(210, 50);
                        Num_Info.Tag = ":Take:" + t + ":User:" + i;
                        Take_Chanel.Controls.Add(Num_Info);

                        Take_Chanel.Height = 90;
                        Take_Chanel.Margin = new Padding(0, 0, 0, 0);
                        Take_Chanel.BackColor = Color.FromArgb(255, 255, 255);
                        Take_Chanel.BorderStyle = BorderStyle.None;
                        Take_Chanel.Dock = DockStyle.Top;
                        Take_Chanel.BorderStyle = System.Windows.Forms.BorderStyle.None;
                        Take_Chanel.Cursor = Cursors.Hand;
                        Take_Chanel.Tag = ":Take:" + t + ":User:" + i;

                        Take_Chanel.Click += new EventHandler(Take_Chanel_Click);
                        Pic_info.Click += new EventHandler(Pic_info_Click);
                        Brie_Info.Click += new EventHandler(Label_Info_Click);
                        Name_Info.Click += new EventHandler(Label_Info_Click);
                        Num_Info.Click += new EventHandler(Label_Info_Click);

                        Take_Chanel.MouseWheel += new MouseEventHandler(OnMouseWheel);
                        Pic_info.MouseWheel += new MouseEventHandler(OnMouseWheel);
                        Brie_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
                        Num_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);
                        Name_Info.MouseWheel += new MouseEventHandler(OnMouseWheel);

                        Take_Chanel.MouseLeave += new System.EventHandler(Take_Chanel_MouseLeave);
                        Take_Chanel.MouseMove += new MouseEventHandler(Take_Chanel_MouseMove);
                        Pic_info.MouseLeave += new System.EventHandler(Pic_info_MouseLeave);
                        Pic_info.MouseMove += new MouseEventHandler(Pic_info_MouseMove);
                        Brie_Info.MouseLeave += new System.EventHandler(Label_Info_MouseLeave);
                        Brie_Info.MouseMove += new MouseEventHandler(Label_Info_MouseMove);
                        Name_Info.MouseLeave += new System.EventHandler(Label_Info_MouseLeave);
                        Name_Info.MouseMove += new MouseEventHandler(Label_Info_MouseMove);
                        Num_Info.MouseLeave += new System.EventHandler(Label_Info_MouseLeave);
                        Num_Info.MouseMove += new MouseEventHandler(Label_Info_MouseMove);

                        Take_Chanel.Controls.Add(Pic_info);
                        if (t == 0)
                        {
                            Chanel1_Info.Controls.Add(Take_Chanel);
                        }
                        if (t == 1)
                        {
                            Chanel2_Info.Controls.Add(Take_Chanel);
                        }
                    }
                }
            }

            Chanel1_Info.AutoSize = true;
            Chanel2_Info.AutoSize = true;
            Calc_Scroll();
            cCalc_Scroll();
        }

        //计算容器高度
        private void Calc_Scroll()
        {
            int scr = 0;
            if (Chanel1_Info.Visible == true)
            {
                scr += Chanel1_Info.Height;
            }
            if (Chanel2_Info.Visible == true)
            {
                scr += Chanel2_Info.Height;
            }
            if (Chanel3_Info.Visible == true)
            {
                scr += Chanel3_Info.Height;
            }

            scr += Chanel_panel1.Height + Chanel_panel2.Height + Chanel_panel3.Height;
            if ((scr - Left_panel.Height) <= 0)
            {
                mouse_Wheel = false;
                Content_panel.Top = 0;
                ScrollHard_panel.Location = new Point(set_x, 0);
            }
            else
            {
                mouse_Wheel = true;
            }
        }

        private void cCalc_Scroll()
        {
            if ((Showinfo_panel.Height- Takeconter_panel.Height) <=0 )
            {
                cmouse_Wheel = false;
                Showinfo_panel.Top = 0;
                TakeScrollHard_panel.Location = new Point(cset_x, 0);
            } else
            {
                cmouse_Wheel = true;
            }
        }

        //鼠标滑轮
        private void OnMouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int set_y = 0;

            Calc_Scroll();
            if (mouse_Wheel) //是否判断鼠标滑轮
            {
                if (e.Delta > 0) //滑轮向上
                {
                    set_y = ScrollHard_panel.Location.Y - 10; //每次移动10
                    if (set_y < 0) { set_y = 0; } //超范围
                }
                if (e.Delta < 0)  //滑轮向下
                {
                    set_y = ScrollHard_panel.Location.Y + 10; //每次移动10
                    if (set_y > limt) { set_y = limt; } //超范围
                }
                ScrollHard_panel.Location = new Point(set_x, set_y); //滚动块的定位

                Content_panel.Top = -set_y; //装内容的panel滚动显示
            }
        }
        //此鼠标滑轮事件与上面固定高度鼠标滑轮事件不同，容器高度不断变化
        private void c_OnMouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            int set_y = 0;

            cCalc_Scroll();
            if (cmouse_Wheel) //是否判断鼠标滑轮
            {
                if (e.Delta > 0) //滑轮向上
                {
                    set_y = TakeScrollHard_panel.Location.Y - 10; //每次移动10
                    if (set_y < 0) { set_y = 0; } //超范围
                }
                if (e.Delta < 0)  //滑轮向下
                {
                    set_y = TakeScrollHard_panel.Location.Y + 10; //每次移动10
                    if (set_y > climt) { set_y = climt; } //超范围
                }
                TakeScrollHard_panel.Location = new Point(cset_x, set_y); //滚动块的定位

                int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt - set_y;
                if (p_set > 0) p_set = 0;
                Showinfo_panel.Top = p_set;
            }
        }

        //自定义滚动条鼠标事件
        private void ScrollHard_panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //鼠标左键
            {
                mouseOff.Y = e.Y;  //取当前位置
                mouse_Press = true; //鼠标按下
            }
        }
        private void ScrollHard_panel_MouseUp(object sender, MouseEventArgs e)
        {
            mouse_Press = false; //鼠标放开
        }
        private void ScrollHard_panel_MouseLeave(object sender, EventArgs e)
        {
            mouse_Wheel = false; //滑轮不可用
        }
        private void ScrollHard_panel_MouseMove(object sender, MouseEventArgs e)
        {
            Calc_Scroll();
            if (mouse_Wheel)   //可以用滑轮
            {
                if (mouse_Press) //鼠标按下状态
                {
                    int set_y = ScrollHard_panel.Top + e.Y - mouseOff.Y; //计算当前纵向坐标
                    if (set_y < 0) { set_y = 0; } //超范围
                    else if (set_y > limt) { set_y = limt; } //超范围
                    else { ScrollHard_panel.Location = new Point(set_x, set_y); } //滚动块的定位
                    Content_panel.Top = -set_y; //装内容的panel滚动显示
                }
            }
        }

        private void TakeScrollHard_panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) //鼠标左键
            {
                cmouseOff.Y = e.Y;  //取当前位置
                cmouse_Press = true; //鼠标按下
            }
        }

        private void TakeScrollHard_panel_MouseUp(object sender, MouseEventArgs e)
        {
            cmouse_Press = false; //鼠标放开
        }
        private void TakeScrollHard_panel_MouseLeave(object sender, EventArgs e)
        {
            cmouse_Wheel = false; //滑轮不可用
        }

        private void TakeScrollHard_panel_MouseMove(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();
            if (cmouse_Wheel)   //可以用滑轮
            {
                if (cmouse_Press) //鼠标按下状态
                {
                    int set_y = TakeScrollHard_panel.Top + e.Y - cmouseOff.Y; //计算当前纵向坐标
                    if (set_y < 0) { set_y = 0; } //超范围
                    else if (set_y > climt) { set_y = climt; } //超范围
                    else { TakeScrollHard_panel.Location = new Point(cset_x, set_y); } //滚动块的定位

                    int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt- set_y;
                    if (p_set > 0) p_set = 0;
                    Showinfo_panel.Top = p_set;
                }
            }
        }

        private void ScrollBar_panel_MouseMove(object sender, MouseEventArgs e)
        {
            Calc_Scroll();  //可以使用滑轮
        }
        private void ScrollBar_panel_MouseLeave(object sender, EventArgs e)
        {
            mouse_Wheel = false; //不可使用滑轮
        }
        private void ScrollBar_panel_MouseUp(object sender, MouseEventArgs e)
        {
            Calc_Scroll();
            if (mouse_Wheel)
            {
                if (e.Button == MouseButtons.Left) //鼠标左键
                {
                    int set_y = e.Y; //当前纵坐标
                    if (set_y > limt) { set_y = limt; } //超范围
                    ScrollHard_panel.Location = new Point(set_x, set_y); //滚动块定位
                    Content_panel.Top = -set_y;//装内容的panel滚动显示
                    mouse_Press = false; //鼠标为放开状态
                }
            }
        }

        private void TakeScrollBar_panel_MouseMove(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();  //可以使用滑轮
        }

        private void TakeScrollBar_panel_MouseLeave(object sender, EventArgs e)
        {
            cmouse_Wheel = false; //不可使用滑轮
        }

        private void TakeScrollBar_panel_MouseUp(object sender, MouseEventArgs e)
        {
            cCalc_Scroll();
            if (cmouse_Wheel)
            {
                if (e.Button == MouseButtons.Left) //鼠标左键
                {
                    int set_y = e.Y; //当前纵坐标
                    if (set_y > climt) { set_y = climt; } //超范围
                    TakeScrollHard_panel.Location = new Point(cset_x, set_y); //滚动块定位
                    Showinfo_panel.Top = -set_y;//装内容的panel滚动显示
                    cmouse_Press = false; //鼠标为放开状态

                    int p_set = Takeconter_panel.Height - Showinfo_panel.Height + climt - set_y;
                    if (p_set > 0) p_set = 0;
                    Showinfo_panel.Top = p_set;
                }
            }
        }

        //栏目鼠标事件
        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            Panel Chanel = (Panel)sender;
            Chanel.BackColor = Color.FromArgb(245, 245, 245);
            Chanel.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Pic_MouseMove(object sender, MouseEventArgs e)
        {
            PictureBox Chanel = (PictureBox)sender;
            Chanel.Parent.BackColor = Color.FromArgb(245, 245, 245);
            Chanel.Parent.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Label_MouseMove(object sender, MouseEventArgs e)
        {
            Label Chanel = (Label)sender;
            Chanel.Parent.BackColor = Color.FromArgb(245, 245, 245);
            Chanel.Parent.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Panel_MouseLeave(object sender, EventArgs e)
        {
            Panel Chanel = (Panel)sender;
            Chanel.BackColor = Color.FromArgb(255, 255, 255);
            Chanel.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
            mouse_Wheel = false;
        }
        private void Pic_MouseLeave(object sender, EventArgs e)
        {
            PictureBox Chanel = (PictureBox)sender;
            Chanel.Parent.BackColor = Color.FromArgb(255, 255, 255);
            Chanel.Parent.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
        }
        private void Label_MouseLeave(object sender, EventArgs e)
        {
            Label Chanel = (Label)sender;
            Chanel.Parent.BackColor = Color.FromArgb(255, 255, 255);
            Chanel.Parent.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
        }
        private void Chanel_panel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (Chanel1_Info.Visible)
            {
                Chanel1_Info.Visible = false;
            }
            else
            {
                Chanel1_Info.Visible = true;
            }
            Calc_Scroll();
        }
        private void Chanel_panel2_MouseClick(object sender, MouseEventArgs e)
        {
            if (Chanel2_Info.Visible)
            {
                Chanel2_Info.Visible = false;
            }
            else
            {
                Chanel2_Info.Visible = true;
            }
            Calc_Scroll();
        }
        private void Chanel_panel3_MouseClick(object sender, MouseEventArgs e)
        {
            if (Chanel3_Info.Visible)
            {
                Chanel3_Info.Visible = false;
            }
            else
            {
                Chanel3_Info.Visible = true;
            }
            Calc_Scroll();
        }
        private void Take_Chanel_MouseMove(object sender, MouseEventArgs e)
        {
            Panel panel = (Panel)sender;
            panel.BackColor = Color.FromArgb(245, 245, 245);
            panel.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Take_Chanel_MouseLeave(object sender, EventArgs e)
        {
            Panel panel = (Panel)sender;
            panel.BackColor = Color.FromArgb(255, 255, 255);
            panel.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
        }
        private void Pic_info_MouseMove(object sender, EventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            pic.Parent.BackColor = Color.FromArgb(245, 245, 245);
            pic.Parent.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Pic_info_MouseLeave(object sender, EventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            pic.Parent.BackColor = Color.FromArgb(255, 255, 255);
            pic.Parent.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
        }
        private void Label_Info_MouseMove(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            label.Parent.BackColor = Color.FromArgb(245, 245, 245);
            label.Parent.Controls[1].BackColor = Color.FromArgb(245, 245, 245);
        }
        private void Label_Info_MouseLeave(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            label.Parent.BackColor = Color.FromArgb(255, 255, 255);
            label.Parent.Controls[1].BackColor = Color.FromArgb(255, 255, 255);
        }

        //写当前会话对象
        private void TakeObjWrite(string Objtag)
        {
            string str = Objtag;
            string[] sArray = str.Split(new char[2] { ':', ':' });
            Takepalt_label.Text = " 当前会话：" + palte[int.Parse(sArray[2]), int.Parse(sArray[4]), 0];
            taketime_label.Text = DateTime.Now.ToString("HH:mm");
            //确定当前频道，通讯时当消息标志使用
            Chanel = int.Parse(sArray[4]);
            uw = false;
            TcpInfo.Clear();
            TcpInfo.AppendText("选择频道：" + Chanel);

            if (OldChanel != Chanel)
            {
                Showinfo_panel.Controls.Clear();
                OldChanel = Chanel;
                Showinfo_panel.Size = new Size(557, 46);
                //切换栏目，向服务器申请该栏目所有信息
                SendString("GetChanel," + Chanel);
            }
        }

        //点击栏目
        private void Take_Chanel_Click(object sender, EventArgs e)
        {
            Panel panel = (Panel)sender;
            TakeObjWrite(panel.Tag.ToString());
        }
        private void Pic_info_Click(object sender, EventArgs e)
        {
            PictureBox Pic = (PictureBox)sender;
            TakeObjWrite(Pic.Tag.ToString());
        }
        private void Label_Info_Click(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            TakeObjWrite(label.Tag.ToString());
        }

        private void Form1_LocationChanged(object sender, EventArgs e)
        {
            Fmx = this.Left;
            Fmy = this.Top;
            if (form2 != null)
            {
                form2.Left = Fmx + 330;
                form2.Top = Fmy + 415;
            }
        }

        //表情窗口，确保只打开1次，不可多开
        private void smail_btn_MouseClick(object sender, MouseEventArgs e)
        {
            if (form2 == null)
            {
                form2 = new Form2(this);
                form2.Left = Fmx + 330;
                form2.Top = Fmy + 415;
                form2.Show();
            }
        }

        //退出程序
        private void Exit_Click(object sender, EventArgs e)
        {
            try{
                Close();
            }
            catch (System.Exception ex)
            {
                //还有线程需要手动关闭 暂时推测是tcp连接的地方
            }

        }


        //通讯
        private void SendString(string str)
        {
            try
            {
                //将字符串写入网络流，此方法会自动附加字符串长度前缀
                bw.Write(str);
                bw.Flush();
                TcpInfo.AppendText("发送：" + str);
            }
            catch
            {
                TcpInfo.AppendText("发送失败!");
            }
        }

        private void ReceiveData()
        {
            while (isExit == false)
            {
                string receiveString = null;
                try
                {
                    //从网络流中读出字符串
                    //此方法会自动判断字符串长度前缀，并根据长度前缀读出字符串
                    receiveString = br.ReadString();
                }
                catch
                {
                    //底层套接字不存在时会出现异常
                   //TcpInfo.AppendText("接收数据失败");
                }
                if (receiveString == null)
                {
                    if (isExit == false)
                    {
                        MessageBox.Show("与服务器失去联系！");
                    }
                    break;
                }
                uw = true;
                getMess = receiveString;
                TcpInfo.AppendText(Environment.NewLine + "接收服务器数据：" + Environment.NewLine + receiveString);
            }
            Close();
        }

        //计算显示框高度和宽度，英文字体和中文以及标点、数字的宽度各不相同，需计算
        private void Calc_PanelWidth(string mess)
        {
            //临时建立一个容器装入内容
            RichTextBox canv_Rich = new RichTextBox();
            //先取全部Rtf的值
            canv_Rich.Rtf = mess;
            //再按照Txt判断文字
            //判断中文
            MatchCollection zh = Regex.Matches(canv_Rich.Text, @"[\u4e00-\u9fa5]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            //判断中文标点
            MatchCollection zhdot = Regex.Matches(canv_Rich.Text, @"[，。；？~！：‘“”’【】（）]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            //判断数字
            MatchCollection en = Regex.Matches(canv_Rich.Text, @"[1234567890]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            //其余为英文，并计算总宽度
            Linewidth = (zh.Count + zhdot.Count) * 13 + en.Count * 8 + (canv_Rich.Text.Length - zh.Count - zhdot.Count - en.Count) * 7;
            //接收数据内容中是否包含图像
            int havePic = 0;
            havePic = Regex.Matches(canv_Rich.Rtf, "Paint.Picture").Count;
            //加上图像宽度
            Linewidth += havePic * 33;
            //判断极值
            if (Linewidth > (26 * 13)) { Linewidth = 26 * 13; }
            if (Linewidth < 40) { Linewidth = 40; }
            if (havePic > 0) { Lineheight = 33; }
            else { Lineheight = 25; }
        }

        //发送数据
        private void send_btn_MouseClick(object sender, MouseEventArgs e)
        {
            if (Chanel != 255)
            {
                TcpInfo.Clear();
                //发送套接字、当前栏目、编辑的内容、用户名、发送时间。
                SendString("Talk," + "$" + Chanel + "$" + Rich_Edit.Rtf + "$"+UserName+"$"+ DateTime.Now.ToString("HH:mm") + "$"+Environment.NewLine);
                Rich_Edit.Clear();
            }
            else
            {
                MessageBox.Show("先选择一个频道！");
            }
        }

        //根据右侧显示内容改变
        private void TcpInfo_TextChanged(object sender, EventArgs e)
        {
            if ((uw == true) & (Chanel != 255) & (getMess != "") )
            {
                string[] sArray = getMess.Split(new char[6] { '[', ']', '$', '$', '$', '$' });
                //sArray[1] 发送信息用户的ip
                //sArray[3] 发送消息的版块
                //sArray[4] 发送消息的内容
                //sArray[5] 用户名
                //sArray[6] 时间

                //计算内容所占的宽度
                Calc_PanelWidth(sArray[4]);

                //是否当前模块
                if (sArray[3] == Chanel.ToString())
                {
                    Panel uTake = new Panel();
                    PictureBox hard_img = new PictureBox();
                    Label u_name = new Label();
                    Panel conter_panel = new Panel();
                    Panel rc = new Panel();
                    //使用改变的PicRichTextBox，为背景透明
                    RichTextBoxEx rich_conter = new RichTextBoxEx();

                    //判断是否本人，本人右侧显示，其他左侧显示
                    if (sArray[5] == UserName)
                    {
                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"res\me.png");
                        Image image = hard_img.Image;
                        Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = newImage;
                        hard_img.Location = new Point(490,10);

                        u_name.Text = "[ User: " + sArray[5] + " for " + sArray[6] + " ]";
                        u_name.AutoSize = true;
                        u_name.ForeColor = Color.FromArgb(195,195,195);
                        u_name.Location = new Point(260,7);

                        rich_conter.Rtf = sArray[4];
                        rich_conter.WordWrap = true;
                        rich_conter.ReadOnly = true;
                        rich_conter.BorderStyle = BorderStyle.None;
                        rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                        rich_conter.Location = new Point(10, 10);
                        rich_conter.ForeColor = Color.FromArgb(255,255,255);
                        rich_conter.BackColor = Color.FromArgb(90, 143, 0);
                        rich_conter.Dock = DockStyle.Fill;
                        rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                        rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                        rc.Controls.Add(rich_conter);

                        rc.BackColor = Color.FromArgb(90, 143, 0);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(10, 10);

                        conter_panel.BackColor = Color.FromArgb(90, 143, 0);
                        conter_panel.Width = Linewidth + 25;
                        conter_panel.Height = Lineheight+20;
                        conter_panel.Location = new Point(480- conter_panel.Width, 30);
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 0, Color.FromArgb(90, 143, 0), Color.FromArgb(90, 143, 0));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }
                    else
                    {
                        hard_img.Size = new Size(64, 64);
                        hard_img.Image = Image.FromFile(@"res\other.png");
                        Image image = hard_img.Image;
                        Image newImage = CutEllipse(image, new Rectangle(0, 0, 200, 200), new Size(64, 64));
                        hard_img.Image = newImage;
                        hard_img.Location = new Point(0, 10);

                        u_name.Text = "[ User: " + sArray[5] + " for " + sArray[6] + " ]";
                        u_name.AutoSize = true;
                        u_name.ForeColor = Color.FromArgb(195, 195, 195);
                        u_name.Location = new Point(70, 7);

                        rich_conter.Rtf = sArray[4];
                        rich_conter.WordWrap = true;
                        rich_conter.ReadOnly = true;
                        rich_conter.BorderStyle = BorderStyle.None;
                        rich_conter.ScrollBars = RichTextBoxScrollBars.None;
                        rich_conter.Location = new Point(10, 10);
                        rich_conter.ForeColor = Color.FromArgb(255, 255, 255);
                        rich_conter.BackColor = Color.FromArgb(0, 122, 204);
                        rich_conter.Dock = DockStyle.Fill;
                        rich_conter.MouseDown += new MouseEventHandler(richconter_MouseClick);
                        rich_conter.ContentsResized += new ContentsResizedEventHandler(rich_ContentsResized);
                        rc.Controls.Add(rich_conter);

                        rc.BackColor = Color.FromArgb(0, 122, 204);
                        rc.Width = Linewidth;
                        rc.Height = Lineheight;
                        rc.Location = new Point(20, 10);

                        conter_panel.BackColor = Color.FromArgb(0, 122, 204);
                        conter_panel.Width = Linewidth + 35;
                        conter_panel.Height = Lineheight + 20;
                        conter_panel.Controls.Add(rc);
                        conter_panel.Location = new Point(70, 30);
                        Bitmap localBitmap = new Bitmap(conter_panel.Width, conter_panel.Height);
                        Graphics bitmapGraphics = Graphics.FromImage(localBitmap);
                        bitmapGraphics.Clear(BackColor);
                        bitmapGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                        Draw(conter_panel.ClientRectangle, bitmapGraphics, 18, true, 1, Color.FromArgb(0, 122, 204), Color.FromArgb(0, 122, 204));
                        conter_panel.BackgroundImage = localBitmap;
                        conter_panel.Controls.Add(rc);
                    }

                    uTake.Controls.Add(hard_img);
                    uTake.Controls.Add(u_name);
                    uTake.Controls.Add(conter_panel);
                    uTake.AutoSize = true;
                    uTake.Dock = DockStyle.Top;

                    uTake.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    hard_img.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    u_name.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    conter_panel.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rich_conter.MouseWheel += new MouseEventHandler(c_OnMouseWheel);
                    rc.MouseWheel += new MouseEventHandler(c_OnMouseWheel);

                    Showinfo_panel.Controls.Add(uTake);
                    Showinfo_panel.AutoSize = true;
                    if (Showinfo_panel.Height>= Takeconter_panel.Height)
                    {
                        Showinfo_panel.Top = Takeconter_panel.Height - Showinfo_panel.Height;
                    }
                    rich_conter.Focus();
                    Rich_Edit.Focus();
                }
                uw = false;

                cCalc_Scroll();
                
                if (Showinfo_panel.Height >= Takeconter_panel.Height)
                {
                    TakeScrollHard_panel.Location = new Point(cset_x, climt);
                    cmouse_Wheel = true;
                }
                
            }
        }

        //不使显示信息框右焦点
        private void richconter_MouseClick(object sender, MouseEventArgs e)
        {
            Rich_Edit.Focus();
        }

        //PicRichTextBox背景透明
        public class RichTextBoxEx : PicRichTextBox
        {
            protected override CreateParams CreateParams
            {
                get
                {
                    CreateParams cp = base.CreateParams;
                    cp.ExStyle |= 0x20;
                    return cp;
                }
            }
        }

        //设置显示信息框高度
        private void rich_ContentsResized(object sender, ContentsResizedEventArgs e)
        {
            Lineheight = e.NewRectangle.Height;// + 10;
        }

        //关闭系统
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //断开连接
            if (client != null)
            {
                SendString("Logout");
                isExit = true;
                br.Close();
                bw.Close();
                client.Close();
            }
        }

        //logo图画设置按鼠标移动窗体
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        private void Logo_panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture(); //释放鼠标捕捉
                SendMessage(Handle, 0xA1, 0x02, 0);
            }
        }

    }
}
